<?php

class Hotel extends MY_Controller {
	
	/**
	 * 'link'=>'name' menu entries
	 * @var array
	 */
	private $menuItems = array (
		'Hotel/index'				=>	'Principal',
		'Hotel/offers'				=>	'Ofertas',
		//'Hotel/extras'				=>	'extras',
		'Hotel/clients'				=>	'Clientes',
		//'Hotel/schools'				=>	'Escolas',
		'Hotel/listReservations'	=>	'Reservas Feitas',
		'Hotel/profile'				=>	'Perfil',
		'Hotel/test'				=>	'Test'
	);
	
	/**
	 * view's to be used with 'template' libray 
	 * @var array
	 */
	var $views = array(
		'hotelBodyMain'             =>'hotel/content/hotelBodyMain',
		'hotelBodyOffers'           =>'hotel/content/hotelBodyOffers',
		'hotelBodySchools'          =>'hotel/content/hotelBodySchools',
		'hotelBodyExtras'           =>'hotel/content/hotelBodyExtras',
		'hotelBodyClients'          =>'hotel/content/hotelBodyClients',
		'hotelBodySchool'         	=>'hotel/content/hotelBodySchool',
		'hotelBodyReservation'      =>'hotel/content/hotelBodyReservation',		
		'hotelBodyListReservations' =>'hotel/content/hotelBodyListReservations',	
		'hotelBodyProfile' 			=>'hotel/content/hotelBodyProfile',	
		'hotelBodyShowReservation'  =>'hotel/content/hotelBodyShowReservation',
		'hotelBodyTest'  			=>'hotel/content/hotelBodyTest' 
	);
	
	
	/**
	 * Constructor 
	 */
	function Hotel() {
		parent::__construct();
		
		if ($this->ion_auth->is_group("hotel")) {
			
			$this->load->helpers(array('html'));
			
			$this->load->library(array('carabiner','template','fuelmenu','ion_auth','session','mylibrary'));
			
			$this->load->model('Hotel_model');
			
			$this->lang->load('hotel');
			
			// $this->carabiner->css('reset.css');
			// $this->carabiner->css('hotel/hotel.css');
		
			$this->_configTemplate();
		
			$this->_setData();
			
			$this->_tmp();
		}
		else {		// not a Hotel user
			redirect('Login/index');
		}
	}
	
	
	/**
	 * config the template data library
	 */
	private function _configTemplate() {
		
		$this->template->title('Radical Booking Hotel: '.$this->ion_auth->get_user()->company);
		
		$this->template->enable_parser(false);
		
		$this->template->set_layout('hotelBootstrapLayout');
		//$this->template->set_layout('hotelLayout');
	}
	
	
	/**
	 * Set global var to be forward to all views
	 */
	private function _setData() {
		
		// data about the current logged in hotel
		$user = $this->Hotel_model->getUserInfo($this->ion_auth->get_user()->id);
		
		$this->template->set('user',$user);
		$this->template->set('hotel',$user);
		$this->template->set('menuItems',$this->menuItems);
		
		$account = array();
		
		if ($this->ion_auth->logged_in()) {
				
			$account['email'] = $this->ion_auth->get_user()->email;
				
			if ($this->ion_auth->is_admin()) {
				$account['type'] = "Admin";
			}
			else if ($this->ion_auth->is_group('school')) {
				$account['type'] = "School";
			}
			else if ($this->ion_auth->is_group('hotel')) {
				$account['type'] = "Hotel";
			}
		}
		else {
			$account = null;
		}
		
		$this->template->set('account',$account);
		
		// set the school associated for this hotel ... one to one ... many to many? 
		//$this->template->set('schoolId', $this->Hotel_model->getSchoolID($this->ion_auth->get_user()->id));
	}
	
	
	/**
	 * Retrieve an array with all schools associated to this hotel .. and the active link school
	 */
	private function _schoolListMenu() {
		
		// get all school IDs associated to this hotel
		$schools = $this->Hotel_model->getHotelASschool($this->ion_auth->get_user()->id);
		
		// an associated array to hold the link=>name used to render the menu
		$nav = array('Hotel/school/0'=>'Todos');
		
		// an array with url segments
		$segment_array = $this->uri->segment_array();
		
		// the last item from the url 
		$lastUriSegment = $segment_array[count($segment_array)];
		
		$active = null;
		
		if ( $lastUriSegment == '0' )
			$active = 'Hotel/school/0';
		
		// iterate through all schools associated to this hotel
		foreach ($schools as $key => $value) {
			
			$nav['Hotel/school/'.$key] = $value;
			
			if ( $key == $lastUriSegment )
				$active = 'Hotel/school/'.$key;
		}
		
		// get the first element of the array
		$firstElement = array_shift(array_keys($nav));
		
		// the first school from the list should be selected ...
		if ($lastUriSegment == 'offers' && $firstElement != null)
			$active = $firstElement;
			
		/*
		$param = array(
			'active_class'			=>'active',
			'use_titles'			=>false,
			'container_tag_class'	=>'nav nav-pills nav-stacked',
		);*/
		//$this->fuelmenu->initialize($param);
		//$menu = $this->fuelmenu->render($nav,$active,null,'basic');
		
		$schoolListMenu['links'] = $nav;
		
		$schoolListMenu['active'] = $active;
		
		return $schoolListMenu;
	}
	
	
	/**
	 * menu with navigation links 
	 * @param string $active set the active link manually
	 */
	private function _navigationMenu($active=null, $active_class='active', $use_titles=false, $container_tag_class='nav nav-pills') {
		
		if ($active)
			$active = $this->uri->rsegment(1).'/'.$active; // append the parameter string to a string with the current controller name
		else 
			$active = $this->uri->rsegment(1).$this->uri->slash_rsegment(2,'leading'); // ... the current url
			
		$param = array(
			//'active_class'			=>'current',
			'active_class'			=>$active_class,
			'use_titles'			=>$use_titles,
			//'container_tag_class'	=>'navigation',
			'container_tag_class'	=>$container_tag_class,
		);
		$this->fuelmenu->initialize($param);
		//$this->firephp->log($this->menuItems,'menuItems');
		//$this->firephp->log($active,'active');
		
		// render the menu
		return $this->fuelmenu->render($this->menuItems,$active,NULL,'basic');
	}
	
	private function _activeLink($active=null) {
		
		if ($active)
			$active = $this->uri->rsegment(1).'/'.$active; // append the parameter string to a string with the current controller name
		else 
			$active = $this->uri->rsegment(1).$this->uri->slash_rsegment(2,'leading'); // ... the current url
		
		if($active == 'Hotel/school') {
			$active = 'Hotel/offers';
		}
		
		return $active;
	}
	
	/**
	 * use this function to load temporary test data 
	 */
	private function _tmp() {
		
	}
	
	
	
	
	
	
	
	
	
	
	
	public function index() {
		
		if ($this->remoteResources)
			$this->template->set('groupLibraries',array('jquery','bootstrap'));
		else 
			$this->template->set('groupLibraries',array('jquery_local','bootstrap_local'));
		
		//$this->template->set('navigationMenu',$this->_navigationMenu(null, 'active',false, 'nav'));
		
		$this->template->set('activeLink', $this->_activeLink());
		
		//$id = $this->Hotel_model->getSchoolID($this->ion_auth->get_user()->id);
		
		$this->template->build($this->views['hotelBodyMain']);
	}
	
	/**
	 * show available schools with links to available offers 
	 */
	public function offers() {
		
		if ($this->remoteResources)
			$this->template->set('groupLibraries',array('jquery','jqueryui','bootstrap'));
		else
			$this->template->set('groupLibraries',array('jquery_local','jqueryui_local','bootstrap_local'));
		
		$this->template->set('classes',$this->Hotel_model->getAllAvailableClasses());
		$this->template->set('schoolListMenu',$this->_schoolListMenu());
		$this->template->set('activeLink', $this->_activeLink());
		
		$this->carabiner->js('hotel/hotelOffers.js');
		
		$this->template->build($this->views['hotelBodyOffers']);
	}
	
	/**
	 * Function called when a school is choosen in offers schools menu
	 * @param $schoolID  
	 */
	public function school($schoolID = null) {
		
		// if schoolID has the value '0' empty function returns true ...  o.O
		if ( empty($schoolID)  && $schoolID != '0' )
			redirect('Hotel');
		
		// when hotel user presses a school link, this id is used to identify the school
		$this->template->set('id',$schoolID);
	
		if ($this->remoteResources)
			$this->template->set('groupLibraries',array('jquery','jqueryui','bootstrap'));
		else
			$this->template->set('groupLibraries',array('jquery_local','jqueryui_local','bootstrap_amelia'));
	
		$this->template->set('schoolListMenu',$this->_schoolListMenu());
		
		$this->template->set('activeLink', $this->_activeLink());
		
		$this->carabiner->js('hotel/hotelOffers.js');
		
		// get available offers from schools associated to this hotel
		if ( $schoolID == '0' || $schoolID == null ) {
			
			$this->template->set('navigationMenu',$this->_navigationMenu('offers'));
			
			$classes = $this->Hotel_model->getAllAvailableClasses();
			
			$this->template->set('classes',$classes);
			
			$this->template->build($this->views['hotelBodyOffers']);
			
			return;
		}
			
		$this->template->set('navigationMenu',$this->_navigationMenu('offers'));
		//$offers 	= $this->Hotel_model->getAvailableOffers($schoolID);
		//$this->template->set('offers',$offers);
		//$classes 	= $this->Hotel_model->getAvailableClasses($schoolID);
		$classes 	= $this->Hotel_model->getAllAvailableClasses($schoolID);
		$this->template->set('classes',$classes);
		$this->template->build($this->views['hotelBodyOffers']);
	}
	
	
	public function extras() {
		
		// witch libraries we need in this view? only those will be loaded in the head view file
		if ($this->remoteResources)
			$this->template->set('groupLibraries',array('jquery','bootstrap_light'));
		else
			$this->template->set('groupLibraries',array('jquery_local','bootstrap_local'));
		
		$this->template->set('navigationMenu',$this->_navigationMenu());
		
		$this->template->build($this->views['hotelBodyExtras']);
	}
	
	public function clients() {
		
		if ($this->remoteResources)
			$this->template->set('groupLibraries',array('jquery_local','','datatables','','','bootstrap'));
		else
			$this->template->set('groupLibraries',array('jquery_local','','datatables_local','','validationEngine','bootstrap_local'));
		
		//$this->template->set('navigationMenu',$this->_navigationMenu());
		
		$this->template->set('activeLink', $this->_activeLink());
		
		//$this->template->set_layout('hotelBootstrapLayout');
		
		$this->template->set_partial('clientForm', 		'hotel/partials/hotelClientForm');
		
		$this->carabiner->css('hotel/hotelClient.css');
		//$this->carabiner->js('hotel/hotel.js');
		$this->carabiner->js('hotel/hotelClients.js');
		
		$this->template->build($this->views['hotelBodyClients']);
	}
	
	public function profile() {
		
		if ($this->remoteResources)
			$this->template->set('groupLibraries',array('jquery','jqueryForm','bootstrap'));
		else
			$this->template->set('groupLibraries',array('jquery_local','jqueryForm_local','bootstrap_local'));
		
		$this->template->set('activeLink', $this->_activeLink());
		
		$this->carabiner->js('hotel/hotelProfile.js');
		
		$this->template->build($this->views['hotelBodyProfile']);
	}
	
	public function schoolsInfo() {
		
	}
	
	
	public function listReservations() {
		
		// witch libraries we need in this view? only those will be loaded in the head view file
		if ($this->remoteResources)
			$this->template->set('groupLibraries',array('jquery','jqueryui','datatables','bootstrap'));
		else
			$this->template->set('groupLibraries',array('jquery_local','jqueryui_local','datatables_local','bootstrap_local'));
		
		$this->template->set('activeLink', $this->_activeLink());
		
		$this->carabiner->js('hotel/hotelListReservation.js');
		
		$this->template->build($this->views['hotelBodyListReservations']);
	}
	
	public function test() {
		if ($this->remoteResources)
			$this->template->set('groupLibraries',array('jquery','ext-core','bootstrap'));
		else
			$this->template->set('groupLibraries',array('','','','bootstrap_local'));
		
		$this->template->set('activeLink', $this->_activeLink());
		
		$this->template->build($this->views['hotelBodyTest']);
	}
	
	/**
	 * Function called when the offer reservation link is pressed  
	 * @param int $classId identification of the class to be reserved
	 * @todo check if the classId is OK
	 */
	function reservation($classId = null) {
		
		//$session = $this->session->all_userdata();
		//$this->firephp->log($session, 'session');
		//$this->firephp->log($_POST, 'POST');
		
		if (!$classId)
			redirect('Hotel/offers');
		
		// get and set the school identification of this class
		$schoolId = $this->Hotel_model->getSchoolID_from_classID($classId);
		$this->template->set('schoolId', $schoolId);
		
		$offerId = $this->db->select('offer_id')->from('class')->where('id',$classId)->get()->row()->offer_id;
		$this->template->set('offerId', $offerId);
		
		// load asset resources 
		if ($this->remoteResources)
			$this->template->set('groupLibraries',array('jquery','jqueryui','datatables','formee','validationEngine','bootstrap_light'));
		else
			$this->template->set('groupLibraries',array('jquery_local','jqueryui_local','datatables_local','formee','validationEngine','bootstrap_light'));
		
		$this->template->set('classId',$classId);
		
		// set the user identification
		$userId = $this->ion_auth->get_user()->id; // hotel identification
		$this->template->set('userId', $userId);
		
		// load the main menu
		$this->template->set('navigationMenu',$this->_navigationMenu('offers'));
		
		// form to create and edit clients
		$this->template->set_partial('clientForm', 'hotel/partials/hotelClientForm');
		
		$this->carabiner->js(array('hotel/hotel.js'));
		$this->carabiner->js(array('hotel/hotelReservation.js'));
		
		// get the school associated to this hotel
		//$schoolId = $this->Hotel_model->getSchoolID($userId);
		
		$this->template->build($this->views['hotelBodyReservation']);
	}
	
	

	/**
	 * Show reservation data
	 * link to show the information about the reservation that is going to be maded 
	 * @param int $clientId
	 * @param int $offerId
	 */
	public function showReservationData($clientId=null, $offerId=null) {
		
		// load asset resources 
		if ($this->remoteResources)
			$this->template->set('groupLibraries',array('jquery','jqueryui','960','bootstrap_light'));
		else
			$this->template->set('groupLibraries',array('jquery_local','jqueryui','960','bootstrap_light'));
		
		// set post data to be viewed in the view
		$post = $_POST;
		$this->template->set('post',$post);
		
		// set the user identification
		$userId = $this->ion_auth->get_user()->id;
		$this->template->set('userId', $userId);
		
		// set information about the reserved offer 
		$offer = $this->Hotel_model->getOffer($post['offerId']);
		$this->template->set('offer', $offer['0']);
		
		// set the information about the extras included by the user
		$extrasIDs = explode('&', $post['extras']);
		if ($extrasIDs)
			$extras = $this->Hotel_model->getExtras($extrasIDs);
		$this->template->set('extras',$extras);
		
		// total and hotelPayment 
		$this->db->select('hotelPayment, transportPrice')->from('sh');
		$this->db->where('hotel_id', 	$userId);
		$this->db->where('school_id', 	$post['schoolId']);
		$row 			= $this->db->get()->row();
		$hotelPayment 	= $row->hotelPayment;
		$transportPrice = $row->transportPrice;
		$total = $offer['0']->offerPrice;
		foreach ($extras as $value) {
			$total += $value->price;
		}
		if ($post['transport']=='yes') {
			$total += $transportPrice;
		}
		else {
			$transportPrice = null;
		}
		$pay2hotel = $total * ($hotelPayment/100);
		$this->template->set('pay2hotel', 		$pay2hotel);
		$this->template->set('hotelPayment', 	$hotelPayment);
		$this->template->set('transportPrice', 	$transportPrice);
		$this->template->set('total',$total);
		
		// information about the school
		$this->template->set('school',$this->Hotel_model->getUserInfo($post['schoolId']));
		
		$this->carabiner->css('hotel/showReservation.css','screen');
		//$this->carabiner->js('hotel/showReservation.js');
		
		// get the school associated to this hotel
		$schoolId = $this->Hotel_model->getSchoolID($userId);
		
		// load the main menu
		$this->template->set('navigationMenu',$this->_navigationMenu('offers'));
		
		// load view
		$this->template->build($this->views['hotelBodyShowReservation']);
	}
	
	
	
	
	
	
	
	
	
	
	
	/**
	 * Create client with data passed in the POST var
	 * Called from 'hotelClients.js'
	 */
	public function createClientAction() {
		
		$okMsg 			= '{"Result":"OK"}';
		$okMsgSucc 		= '{"Result":"OK","title":"client criado","msg":"O cliente foi criado com sucesso"}';
		$errGeneric 	= '{"Result":"ERROR","msg":"generic error"}';
		
		$users_id = $this->ion_auth->get_user()->id;
		
		$client = array(
			'name' 			=>$_POST['name'],
			'address' 		=>$_POST['address'],
			'email'			=>$_POST['email'],
			'phone' 		=>$_POST['phone'],
			'birthday' 		=>$_POST['birthday'],
			'sex'			=>$_POST['sex'],
			'height'		=>$_POST['height'],
			'weight'		=>$_POST['weight'],
			'nationality'	=>$_POST['nationality'],
			'info'			=>$_POST['info']
		);
		
		$succ = $this->Hotel_model->createClient($client);
		
		if ($succ) {
			
			$id = $this->db->insert_id();
			
			if ($_POST['languages']) {
				
				$this->Hotel_model->updateClientLanguage($id, $_POST['languages']);
			}
			
			echo $okMsgSucc;
			return;
		}
		else {
			echo $errGeneric;
			return;
		}
		
		return;
	}
	
	
	
	
	/**
	 * feed datatable jquery plugin with clients
	 */
	public function readClientAction() {
		
		$clients = $this->Hotel_model->getClient();
		
		$dataTableResult['data'] = $clients;
		
		echo json_encode($dataTableResult);
	}
	
	
	
	
	
	public function updateClientAction() {
		
		$okMsg 			= '{"Result":"OK"}';
		$okMsgSucc 		= '{"Result":"OK","msg":"<h2>Cliente actualizado</h2>"}';
		$errGeneric 	= '{"Result":"ERROR","msg":"Não foi possivel actualizar o cliente"}';
		$nullMsg 		= '{"Result":"OK","msg":"null"}';
	
		$user_id = $this->ion_auth->get_user()->id;
		
		if (!$_POST['clientId']) {
			echo $errGeneric;
			return;
		}
		
		//$this->firephp->log($_POST,'post = ');

		if ($_POST['languages']) {
			$this->Hotel_model->updateClientLanguage($_POST['clientId'], $_POST['languages']);
		}
		else {
			$this->db->delete('client_language',array('client_id'=>$_POST['clientId']));
		}
		
		$data = array(
			'name' 			=>$_POST['name'],
			'address' 		=>$_POST['address'],
			'email'			=>$_POST['email'],
			'phone' 		=>$_POST['phone'],
			'birthday' 		=>$_POST['birthday'],
			'sex'			=>$_POST['sex'],
			'height'		=>$_POST['height'],
			'weight'		=>$_POST['weight'],
			'nationality'	=>$_POST['nationality'],
			'info'			=>$_POST['info']
		);
		//$this->firephp->log($data);

		$this->db->where('id',$_POST['clientId']);
		$upt = $this->db->update('client',$data);
		
		if ($upt) {
			echo $okMsgSucc;
		}
		else {
			echo $errGeneric;
		}
		
		return;
	}
	
	
	
	
	
	public function deleteClientAction() {
		
		$okMsg 			= '{"Result":"OK"}';
		$okMsgSucc 		= '{"Result":"OK","msg":"client eliminado com sucesso"}';
		$errGeneric 	= '{"Result":"ERROR","msg":"Não foi possivel eliminar o cliente"}';
		$nullMsg 		= '{"Result":"OK","msg":"null"}';
		
		$user_id = $this->ion_auth->get_user()->id;
		
		//$this->firephp->log($_POST, 'POST: ');
		$this->firephp->log($_POST['clientId'], 'clientId: ');
		
		if ($_POST['clientId']) {
			
			$succ = $this->db->delete('client',array('id'=>$_POST['clientId'],'users_id'=>$user_id));
		
			if ($succ) {
				echo $okMsgSucc;
				return;
			}
			else {
				echo $errGeneric;
				return;
			}
		}
		else {
			echo $nullMsg;
			return;
		}
	}
	
	
	
	
	
	
	
	/**
	 * Function called when reservation button is pressed in the view 'hotelBodyShowReservation'
	 */
	public function createReservationAction() {
		
		// messages to send
		$ok 					= '{"Result":"OK","msg":"Reserva efectuada com sucesso"}';
		$errGeneric 			= '{"Result":"ERROR","msg":"Não foi possivel fazer a reserva"}';
		$errTest 				= '{"Result":"ERROR","msg":"teste"}';
		$errClient 				= '{"Result":"ERROR","msg":"Cliente ja esta registado para esta oferta"}';
		$errFull 				= '{"Result":"ERROR","msg":"Não existem vagas disponiveis"}';
		$errClassFull 			= '{"Result":"ERROR","msg":"Não existem vagas para esta aula"}';
		$errOfferNotAvailable 	= '{"Result":"ERROR","msg":"Esta oferta não está disponivel"}';
		$testMsg				= '{"Result":"OK","msg":"mensagem de test"}';
		
		//$this->firephp->log($_POST);
		
		$offerId 	= $_POST['offerId'];
		$classId 	= $_POST['classId'];
		$clientId 	= $_POST['clientId'];
		$userId 	= $_POST['userId']; // hotel identification
		$extras 	= $_POST['extras']; // extras added to the offer by the client
		
		// array: total, pay2hotel, hotelPayment
		$price = $this->session->userdata('price');
		//$this->firephp->log($price, 'price: ');
		
		$now 		= date('Y-m-d H:i:s',time());
		
		if ($this->Hotel_model->isClassFull($classId)) {
			echo $errClassFull;
			return;
		}
		
		$reserve = $this->Hotel_model->getReserveInfo(50);
		//$this->firephp->log($reserve, 'reserve: ');
		
		//echo $testMsg;
		//return;
		
		// new client? save him ...
		if ( !$clientId ) {
			
			$newClient = $this->session->userdata('newClient');
			
			$client = array(
				'name' 			=>$newClient['name'],
				'address' 		=>$newClient['address'],
				'email'			=>$newClient['email'],
				'phone' 		=>$newClient['phone'],
				'birthday' 		=>$newClient['birthday'],
				'sex'			=>$newClient['sex'],
				'height'		=>$newClient['height'],
				'weight'		=>$newClient['weight'],
				'nationality'	=>$newClient['nationality'],
				'info'			=>$newClient['info']
			);
		
			$succ = $this->Hotel_model->createClient($client);
			
			if ($succ)
				$clientId = $succ;
			else {
				echo $errGeneric;
			}
		}
		
		// store the extras IDs in an Array
		$trimed = trim($extras,'&');
		$arrExtras = array();
		if($trimed)
			$arrExtras = explode('&', $trimed);
		// --------------------------------
		
			if ($this->Hotel_model->isClienteInReservationList($clientId, $classId)) {
				echo $errClient;
				return;
			}
			else { 
				
				// create record
				$clientResData = array(
					'reserves_id' 	=> null,
					'client_id' 	=> $clientId,
					'date' 			=> $now,
					'offer_tmp_id' 	=> $offerId,
					'class_id'		=> $classId,
					'total'		 	=> $price['total'],
					'hotelPayment'	=> $price['hotelPayment'],
					'transportPrice'=> $price['transportPrice']
				);
					
				$succ = $this->db->insert('reserve',$clientResData);
					
				if ($succ) {
					
					$reserveId = $this->db->insert_id();
					
					// EXTRA_RESERVES
					$this->Hotel_model->addExtra_Reserves($this->db->insert_id(),$arrExtras);
					
					$class = $this->db->select('offer_id, maxPart, part')->from('class')->where('id',$classId)->get()->row();
					$part = $class->part;
					//$part = $this->db->select('part')->from('class')->where('id',$classId)->get()->row()->part;
					
					// ... it is the last reservation?
					if ($class->maxPart == ($class->part + 1)) {
						
						// enable offer
						$offer = $this->db->select('numberOfClasses')->from('offer')->where('id', $class->offer_id)->get()->row();
						$this->db->update('offer', array('remainingClasses'=>$offer->numberOfClasses,'part'=>0), array('id'=>$class->offer_id));
					}
					
					// increment the participant number
					$part++;
					$this->db->update('class',array('part'=>$part),array('id'=>$classId));
				
					echo $ok;
					return;
					
					// send email here ...
					$this->load->library('email');
					$this->email->from('me@mail.com', 'name');
					$this->email->to('someone@mail.com');
					$this->email->cc('another@mail.com');
					$this->email->subject('Email test');
					$this->email->message('Testing the email');
					$this->email->send();
				}
				else {
					echo $errGeneric;
					return;
				}
			}
		
		echo $errGeneric;
		return;
	}
	
	
	
	
	/**
	 * Called from 'hotelBodyListReservation'
	 */
	public function readReservationAction() {
		
		$noData 	= '{"data":[]}';
		
		$user_id = $this->ion_auth->get_user()->id;
		
		$now = date('Y-m-d H:i:s',time());
		
		//$offerId 	= $_POST['offerId'];
		//$start		= $_POST['start'];
		//$end		= $_POST['end'];
		
		// javascript null val is passed as a string
		//if ( $start == 'null' ) $start = null;
		//if ( $end == 'null' ) 	$start = null;
		
		// will hold class IDs with schedules between a date range
		$classesInRange = array();
		
		// only enter here if a date range is specified
		//if ( $start != null && $end != null ) {
		if (false) {
			
			$classesInRange = $this->Hotel_model->getClassesWithSchedulesInRange($start, $end);
			
			// if no schedules in the range, no data should be returned
			if (empty($classesInRange)) {
				echo $noData;
				return;
			}
		}

		// retrieve information about clients with reservation
		$selectFields = '
			client.id				as clientId,
			client.name				as clientName,
			offer.name 				as offerName,
			client.email 			as email,
			client.phone 			as phone,
			reserve.date	as date
		';
		
		//$this->db->select('*')->from('client');
		$this->db->select($selectFields);
		$this->db->from('client');
		$this->db->join('users','users.id = client.users_id','inner');
		$this->db->where('users.id', $user_id);
		//$this->db->join('meta','meta.user_id = users.id','inner');
		$this->db->join('reserve','reserve.client_id = client.id','inner');
		$this->db->join('class','class.id = reserve.class_id','inner');
		$this->db->join('offer','offer.id = class.offer_id','inner');
		$result = $this->db->get()->result();
		//$this->firephp->log($result);

		// encode to json
		
		// deliver the data
		
		//echo $noData;	
		$dataTableResult['data'] = $result;
		echo json_encode($dataTableResult);
		return;
		
		
		$offerId = null; $reserves = null; 
		$user_id = $this->ion_auth->get_user()->id;
		
		$now = date('Y-m-d H:i:s',time());
		
		$schedules = array();
		$result = $this->db->select('reserves_id')->from('schedule')->where('start >', $now)->get()->result();
		
		foreach ($result as $value) {
			array_push($schedules, $value->reserves_id);
		}
		
		// remove duplicate values
		$schedules = array_unique($schedules);
		$schedules = array_values($schedules);
		
		//$this->db->select('*');
		//$this->db->select('offer.name as offerName, client.name as clientName, email, phone, date');
		$this->db->select('client.id as clientId, offer.name as offerName, client.name as clientName, email, phone, date');
		$this->db->from('reserve');
		$this->db->join('client','client.id = reserve.client_id');
		$this->db->where('client.users_id',$user_id);
		$this->db->join('reserves','reserves.id = reserve.reserves_id');
		$this->db->join('offer','offer.id = reserves.offer_id');
		
		if ($offerId) {
			$this->db->where('offer.id', $offerId);
		}
		
		if ($reserves == 'inactive') {
			$this->db->where('offer.remainingClasses  !=', 0);
		}
		
		if ($reserves == 'active') {
			$this->db->where('offer.remainingClasses', 0);
		}
		
		
		$rows = $this->db->get()->result();
		
		$dataTableResult['data'] = $rows;
		
		echo json_encode($dataTableResult);
	}
	
	
	
	/**
	 * retrieve the schedules from the classId and userId
	 * called from 'hotelOffers.js'
	 */
	public function readScheduleAction() {
		
		$offerId 	= $_GET['data']['offerId'];
		$userId 	= $_GET['data']['userId'];
		$classId	= $_GET['data']['classId'];
		
		$schedules = $this->Hotel_model->getSchedule($classId,$userId);
		
		echo json_encode($schedules);
		
		return;
	}
	
	
	/**
	 * Retrieve the information about a specific offer
	 * @todo validate GET fields
	 */
	public function readOfferAction() {
		
		//$this->firephp->log($_GET, 'GET');
		//$offer = $this->Hotel_model->getOffer($_GET['offerId'],$_GET['userId']);
		$offer = $this->Hotel_model->getOffer($_GET['offerId']);
		//$this->firephp->log($offer, 'offer');
		echo json_encode($offer);
	}
	
	
	public function readExtraAction() {
		
		$offerId 	= $_POST['offerId'];
		$schoolId 	= $_POST['schoolId'];
		
		$extras = $this->Hotel_model->getExtras(null,$offerId, $schoolId,false);
		
		echo json_encode($extras);
		
		return;
	}
	
	
	/**
	 * function used to retrieve the languages that a given client speak.
	 * The 'clientId' is sent with the POST method
	 */
	public function clientLanguages() {
		$this->db->select('language_id,domain')->from('client_language')->where('client_id',$_POST['clientId']);
		$lang = $this->db->join('language', 'language.id=client_language.language_id')->get()->result();
		echo json_encode($lang);
		return;
	}
	
	/**
	* Logout the Hotel user from the system
	*/
	public function logout() {
		$this->ion_auth->logout();
		redirect('Main/index');
	}
	

	
	public function setHotelData() {
		
		$okMsg 					= '{"Result":"OK", 		"msg":"Dados alterados"}';
		$errMsg 				= '{"Result":"ERROR", 	"msg":"erro"}';
		$errNoDataMsg 			= '{"Result":"ERROR", 	"msg":"Sem dados"}';
		$errAllFieldsNeeded 	= '{"Result":"ERROR", 	"msg":"É necessário preencher todos os campos"}';
		$errInvalidValueMsg 	= '{"Result":"ERROR", 	"msg":"Valores inválidos"}';
		$errNotSetMsg 			= '{"Result":"ERROR", 	"msg":"Não foi possivel actualizar os valor"}';
		$data 					= '{"var01":"val01","var02":"val02"}';
		
		//$this->firephp->log($_POST, 'post: ');
		
		$user_id = $this->ion_auth->get_user()->id;
		
		$required = array('hotelCompany', 'hotelPhone', 'hotelAddress');
		
		$error = FALSE;
		
		foreach ($required as $field) {
			if (empty($_POST[$field]) )
				$error = TRUE;
		}
		
		if ($error) {
			echo $errAllFieldsNeeded; 
			return;
		}
		
		$data = array(
			'company' 			=> $_POST['hotelCompany'],
			'phone' 			=> $_POST['hotelPhone'],
			'address' 			=> $_POST['hotelAddress']
		);
		
		$this->db->where('user_id', $user_id);
		
		$succ = $this->db->update('meta', $data);
		
		if ($succ) {
			
			echo $okMsg;
			return;
		}
		else {
			
			echo $errNotSetMsg;
			return;
		}
	}
	
	
	
	
	
	
	
	
	
	/**
	 * For test purposes only
	 */
	public function tmp() {
		
		
		$testMsg				= '{"Result":"OK","msg":"mensagem de test"}';
		$ok						= '{"Result":"OK","msg":"ok"}';
		$error					= '{"Result":"OK","msg":"error"}';
	
		$classId = 28;
		$offerId = 5;
		$schoolId = 7;
		//$users_id = 5;
		$users_id = $this->ion_auth->get_user()->id;
		
		$addrJScalls = $this->mylibrary->getAddressJScalls();
		
		$this->firephp->log($addrJScalls);
		
		
		$client = array(
			'users_id' => $users_id,
			'name' => 'adriano',
			'address' => 'adddress',
			'email' => 'adriano@mail.com',
			'phone' => '2222222',
			'birthday' => '1980-07-23',
			'sex' => 'm',
			'height' => '180',
			'weight' => '90',
			'nationality' => 'pt',
			'info' => 'information',
			'test' => 'test'
		);
		
		$this->load->library('email');
		
		
		$this->email->from('me@mail.com', 'name');
		$this->email->to('someone@mail.com');
		$this->email->cc('another@mail.com');
		$this->email->subject('Email test');
		$this->email->message('Testing the email');
		$this->email->send();
		
		echo $this->email->print_debugger();
		
		return;
		
		
		$this->Hotel_model->createClient($client);
		
		$now = date('Y-m-d H:i:s',time());
		
		$fakeNow = '2012-05-04 12:00:00';
		
		$test = null;
		
		return;
		
		$this->db->select('users_id')->from('class')->where('class.id', $classId);
		$this->db->join('offer','offer.id = class.offer_id','inner');
		$result = $this->db->get()->row()->users_id;
		
		$this->firephp->log($result);
		
		return;
		
		$this->session->unset_userdata('schoolId');
		$this->session->unset_userdata('myvar');
		
		if (empty($test))
			$this->firephp->log('true');
		else
			$this->firephp->log('false');
		
		return;
		
		//$result = $this->Hotel_model->getClassesWithSchedulesInRange(null, null);
		//$this->firephp->log($result);
		
		//$schoolIDs = $this->Hotel_model->getSchools();
		//$this->firephp->log($schoolIDs);
		//$result = $this->db->select('school_id')->from('sh')->where('hotel_id', $users_id)->get()->result();
		$result = $this->Hotel_model->getAllAvailableClasses();
		$this->firephp->log($result);
		if (!$result)
			$this->firephp->log('empty');
		else
			$this->firephp->log('data');
		//$result = $this->Hotel_model->getAllAvailableClasses();
		
		return;	
		
		// select classes with schedules below the current date
		$this->db->select('class_id')->from('schedule');
		$this->db->join('class','class.id = schedule.class_id','left outer');
		$this->db->where('start >', $now);
		$this->db->group_by('class_id');
		$result = $this->db->get()->result();
		
		// array with class id's with future schedules
		$classIDs = array();
		
		foreach ($result as $item) {
			array_push($classIDs, $item->class_id);
		}
		
		$this->firephp->log($classIDs,'classIDs');
		
		
		$this->db->select('class_id')->from('schedule');
		$this->db->join('class','class.id = schedule.class_id','left outer');
		$this->db->where('start <', $now);
		$this->db->where_in('class_id',$classIDs);
		$this->db->group_by('class_id');
		$result = $this->db->get()->result();
		
		$classInExecution = array();
		
		foreach ($result as $item) {
			array_push($classInExecution, $item->class_id);
		}
		
		$this->firephp->log($classInExecution,'class in execution');
		//$this->firephp->log(array_diff($classIDs, $id2remove),'diff');
		$this->firephp->log(array_diff($classIDs, $classInExecution),'diff');
		
		echo json_encode($result);
		return;
		
		$offerId = 11;
		$clientId = 2;
		$userId = 8;
		
	
		$extrasIDs = '2&6';
		$trimed = trim($extrasIDs,'&');
		$exploded = explode('&', $trimed);
		$this->firephp->log($extrasIDs);
		$this->firephp->log($trimed);
		$this->firephp->log($exploded);
		
		
		
		
		//$schedule = $this->Hotel_model->getSchedule($offerId,$userId);
		//echo json_encode($schedule);

		//$available = $this->Hotel_model->isOfferAvailableForReservation($offerId);
		//$clients = $this->Hotel_model->getClientsInOffer($offerId);
		//$this->firephp->log($clients,'clients');
		
		
		return;
	}
	
}